<template>
  <div class="upload-file">
    <!-- :limit="limit" -->
    <el-upload
      multiple
      :action="uploadFileUrl"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :show-file-list="false"
      :headers="headers"
      class="upload-file-uploader"
      ref="fileUpload"
    >
      <!-- 上传按钮  -->
      <el-select v-model="valuemodel" placeholder="请选择上传文件类别" >
        <el-option v-for="item in categorydic" :key="item.value" :label="item.label" :value="item.value" >
        </el-option>
      </el-select>
      <el-button v-if="showTip" type="primary" :disabled="isDisabled()" style="margin-left: 30px;">选取文件</el-button>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>

      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
      </template>
      的文件
    </div>
    <!-- 文件列表 -->
    <transition-group
      class="upload-file-list el-upload-list el-upload-list--text"
      name="el-fade-in-linear"
      tag="ul">
      <li :key="file.uid" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <!--  -->
        <el-link :underline="false" target="_blank" @click="lookDown(file)" :href="`${baseUrl}${uploadBaseUrl}?fileName=${file.filePath}`">
          <span class="el-icon-document">
            {{
              getFileName(file.originalFilename || file.fileName || file.name)
            }}
          </span>
        </el-link>
        <!-- <div class="fileName" @click="lookDown(file)">
          {{
            getFileName(file.originalFilename || file.fileName || file.name)
          }}
        </div> -->
        <label v-if="file.categoryname || file.fileSecondCategroy">{{ '类型' + (file.categoryname || file.fileSecondCategroy) }}</label>
        <div class="ele-upload-list__item-content-action">
          <el-link
            v-if="showTip"
            :underline="false"
            :disabled="isDisableds()"
            @click="handleDelete(index)"
            type="danger"
            >删除</el-link
          >
        </div>
      </li>
    </transition-group>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { nextTick, onMounted, ref, watchEffect } from "vue";
// import download from "@/plugins/download";

import { useRouter, useRoute } from "vue-router";
import { getCategorydicApi } from '@/api/project/conversion';
import { el } from "element-plus/es/locales.mjs";

// [{
//   value: 'A',
//   label: 'A:项目管理纲领文件'
// }, {
//   value: 'B',
//   label: 'B:项目前期资料'
// }, {
//   value: 'C',
//   label: 'C:开工准备资料'
// }]
onMounted(async () => {
  await getcategorydata();
});

const getcategorydata = async()=>{
  let response = await getCategorydicApi();
  if (response.code === 200 && response.rows.length > 0) {
    let data = [];
    for(let i=0,len = response.rows.length; i<len; i++){
      data.push({ 
        value: response.rows[i].nickName, 
        label: response.rows[i].nickName+':'+response.rows[i].catgoryName
      });
    }
    categorydic = data;
  } else {
    console.log(err);
  }
}
let categorydic = [];
let valuemodel = ref('');

const route = useRoute();

const props = defineProps({
  modelValue: [String, Object, Array],
  fileList: {
    type: Array,
    default: () => [],
  },
  // 数量限制
  // limit: {
  //   type: Number,
  //   default: 5,
  // },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1024,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg', jpg,.png,.jpeg,.mp4,.mov,.avi"] ["png","jpg","jpeg","mp4","mov","avi"]
  fileType: {
    type: Array,
    default: () => [
      "doc",
      "docx",
      "xls",
      "xlsx",
      "ppt",
      "txt",
      "pdf",
      "zip",
      "rar",
      "png",
      "jpg",
      "jpeg",
    ],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  flag: {
    type: Boolean,
    default: false,
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const uploadBaseUrl = "/common/download";

const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);

watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      let temp = 1;
      // 首先将值转为数组
      const list = Array.isArray(val) ? val : props.modelValue.split(",");
      // 然后将数组转为对象数组
      fileList.value = list.map((item) => {
        if (typeof item === "string") {
          item = { name: item, url: item };
        }
        
        item.uid = item.uid || new Date().getTime() + temp++;
        
        // if(!(item.category && (item.categoryname || item.fileSecondCategroy))){
        //     if(!(item.category)){
        //       item.category = valuemodel.value;
        //     }
        //     let indextrue = categorydic.map(o=>o.value == item.category).indexOf(true);
        //     item.categoryname = categorydic[indextrue].label;
        //     item.fileSecondCategroy = categorydic[indextrue].label;
        // }
        return item;
      });
    } else {
      fileList.value = [];
      return [];
    }
  },
  { deep: true, immediate: true }
);

let localValue = props.modelValue;

watchEffect(() => {
  // 在组件内部
  nextTick(() => {
    // 这里的代码将在 DOM 更新后执行，父组件不能修改，
    localValue = fileList.value;
  });
});

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  if(valuemodel.value == ''){
    proxy.$modal.msgError(
        `请先选择文件类型!`
      );
      return false;
  }
  // 校检文件类型
  if (props.fileType.length) {
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      proxy.$modal.msgError(
        `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
      );
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

const disabled = ref(true);
// 上传按钮禁用
function isDisabled() {
  if (route.query.name === "3" && route.query.task === "2") {
    if(route.query.nametype && route.query.nametype == "成果交付新增" && props.flag){
      return (disabled.value = true);
    }
    else{
    // 任务反馈那块展示
      return (disabled.value = false);
    }
  }
  if (route.query.name === "3" && route.query.contractStatus) {
    // 合同
    return (disabled.value = false);
  }
  if (route.query.name === "3" || props.flag || route.query.name === "5") {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
}

// 删除按钮禁用
function isDisableds() {
  if (route.query.name === "3" && route.query.task === "2") {
    if(route.query.nametype && route.query.nametype == "成果交付新增" && props.flag){
      return (disabled.value = true);
    }
    else{
    // 任务反馈那块展示
      return (disabled.value = false);
    }
  }
  if (route.query.name === "3" && route.query.contractStatus) {
    // 合同
    return (disabled.value = false);
  }
  if (route.query.name === "3" || props.flag || route.query.name === "5") {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
}

// 上传成功回调
function handleUploadSuccess(res, file, fileList) {
  // console.log( res && res.fileInfo,)

  let indextrue = categorydic.map(o=>o.value == valuemodel.value).indexOf(true);
  if (res.code === 200) {
    uploadList.value.push({
      name: res.fileInfo.originalFilename,
      originalFilename: res.fileInfo.originalFilename,
      url: res.fileInfo.url,
      filePath: res.fileInfo.url,
      categoryname : categorydic[indextrue].label,
      fileSecondCategroy : categorydic[indextrue].label
    });

    uploadedSuccessfully();
  } else {
    number.value--;
    proxy.$modal.closeLoading();
    proxy.$modal.msgError(res.msg);
    proxy.$refs.fileUpload.handleRemove(file);
    uploadedSuccessfully();
  }
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);

  emit("update:modelValue", listToString(fileList.value), index, "delete");
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value
      .filter((f) => f.url !== undefined)
      .concat(uploadList.value);

    uploadList.value = [];
    number.value = 0;
    for(let i=0,len = fileList.value.length;i<len; i++){
      fileList.value[i].filePath = fileList.value[i].filePath.substring(fileList.value[i].filePath.indexOf('/profile'));
      fileList.value[i].url = fileList.value[i].url.substring(fileList.value[i].url.indexOf('/profile'));
    }
    emit(
      "update:modelValue",
      listToString(fileList.value),
      fileList && fileList.value,
      "success"
    );
    proxy.$modal.closeLoading();
  }
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if (list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != "" ? strs.substr(0, strs.length - 1) : "";
}

//下载
const lookDown = async (val) => {
  // proxy.$download.name(val.filePath);
  download.name("/common/download/?fileName=" + val.filePath);
};
</script>

<style scoped lang="scss">
.upload-file{
  width: 350px;
}
.upload-file-uploader {
  margin-bottom: 5px;
}
.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}
.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}
.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}
.btn {
  color: #fff;
  background-color: #409eff;
}
.is-disabled {
  // background-color: #8caadf;
}
</style>
